home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 11806 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.2 KB  |  64 lines

  1. Path: inforamp.net!ts14-03
  2. From: rmorin@inforamp.net (Randy Charles Morin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Casting
  5. Date: Sat, 16 Mar 96 08:54:09 GMT
  6. Organization: MiddleWorld SoftWare
  7. Message-ID: <4idvk3$pc1@sam.inforamp.net>
  8. References: <3146DB9C.4022@cs.bham.ac.uk>
  9. NNTP-Posting-Host: ts14-03.tor.inforamp.net
  10. X-Newsreader: News Xpress Version 1.0 Beta #4
  11.  
  12. In article <3146DB9C.4022@cs.bham.ac.uk>,
  13.    Matthew G Butler <M.G.Butler-MSCSE95@cs.bham.ac.uk> wrote:
  14. >Can anyone tell me how to cast from one data type to another? What is
  15. >the syntax? Do I have to cast explicitly or can I stick a casting
  16. >function into my ADT and let the sprites sort it out.
  17.  
  18. #1
  19. If you wan't to cast, say a void * to a int *, try the following.
  20.  
  21. void * p;
  22. int * i;
  23. ..
  24. i = (int *)p;
  25.  
  26. This is just an example.
  27.  
  28. #2
  29. Another way of casting is by writing copy constructors.
  30.  
  31. Example:
  32.  
  33. class MyClass
  34. {
  35. public:
  36.     MyClass();
  37.     MyClass(int &i);    
  38.     int i;
  39. };
  40.  
  41. MyClass::MyClass() {i=0};
  42. MyClass::MyClass(int &a) {i=a};
  43.  
  44. #3
  45. Also you can write implicit casting routines.  The following routine adds an 
  46. integer to a MyClass without casting.
  47.  
  48. class MyClass
  49. {
  50. public:
  51.     int i;
  52.     MyClass& operator+ (int&);
  53. };
  54.  
  55. MyClass& MyClass::operator+ (int& a)
  56. {
  57.     i += a;
  58.     return *this;
  59. };
  60.  
  61. I hope this is enough
  62.  
  63. Agrivar
  64.